package com.heima.search.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.feign.article.ArticleFeignClient;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.media.dtos.WmNewsDownOrUpDTO;
import com.heima.search.pojo.ArticleDoc;
import com.heima.search.service.ApArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author Fuqiang
 * @since :2023-03-31
 */
@Slf4j
@Service
public class ApArticleSearchServiceImpl implements ApArticleSearchService {


    @Autowired
    ArticleFeignClient articleFeignClient;

    @Autowired
    RestHighLevelClient client;

    private static final String INDEX_NAME = "app_info_article";

    @Override
    public void onArticleCreate(Long articleId) {

        // 调用feignclient 查询article信息
        ArticleDto dto = articleFeignClient.findById(articleId);

        ArticleDoc articleDoc = new ArticleDoc(dto);
        // 存储至Es
        IndexRequest indexRequest = new IndexRequest(INDEX_NAME).id("" + articleId);
        indexRequest.source(JSONObject.toJSONString(articleDoc), XContentType.JSON);

        try {
            client.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("es增量添加文章信息失败");
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }

    }

    /**
     * 当article上下架时执行, 上架新增至es, 下架从es中删除
     *
     * @param dto
     */
    @Override
    public void onArticleUpOrDown(WmNewsDownOrUpDTO dto) {
        // 如果dto为空 直接结束
        if (dto == null) {
            return;
        }
        if (dto.getIsDown()) {
            // 删除
            DeleteRequest deleteRequest = new DeleteRequest(INDEX_NAME).id("" + dto.getArticleId());
            try {
                client.delete(deleteRequest, RequestOptions.DEFAULT);
            } catch (IOException e) {
                log.error("文章下架, es删除文章信息失败,articleId = {}", dto.getArticleId());
                throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
            }


        } else {
            // 新增
            this.onArticleCreate(dto.getArticleId());
        }

    }
}
